"""
自动获取项目中所有的url
"""
from collections import OrderedDict  # 导入有序字典模块
from django.conf import settings
from django.utils.module_loading import import_string
from django.urls import URLPattern,URLResolver
import re

def check_url_exclude(url):
    """
    过滤符合条件的url
    :param url:
    :return:
    """
    exclude_url=[
            '/admin/.*',
            '/login/',
            '/logout/',
            '/index/',
    ]
    for regex in exclude_url:
        if re.match(regex,url):
            return  True
def recursion_urls(pre_namespace, pre_url, urlpatterns, url_ordered_dict):
    """

    :param pre_namespace: namespace前缀 'rbac:xxx',用于拼接name
    :param pre_url: url的前缀， 用于拼接url
    :param urlpatterns: 路由关系列表
    :param url_ordered_dict:用于保存递归中所有的路由 # {'rbac:menulist':{'name':'xxx',url:'xxxxx'}}
    :return:
    """
    # 对url 类型判断
    for item in urlpatterns:
        if isinstance(item, URLPattern):  # 非路由分发，将路由添加到字典中
            if not item.name:
                continue
            if pre_namespace:
                name = '%s:%s'%(pre_namespace,item.name)
            else:
                name = item.name
            # 对url进行拼接
            url = pre_url + str(item.pattern) # 获取完整的url
            url = url.replace('^','').replace('$','')
            if check_url_exclude(url):
                continue
            url_ordered_dict[name] = {'alias':name,'url':url}
        elif isinstance(item, URLResolver):  # 路由分发，递归操作
            # 如果有多个namespace 则拼接
            if pre_namespace:
                if item.namespace:
                    namespace = '%s:%s'%(pre_namespace,item.namespace)
                else:
                    namespace=item.namespace
            else:
                if item.namespace:
                    namespace = item.namespace
                else:
                    namespace = None
            recursion_urls(namespace, pre_url+str(item.pattern), item.url_patterns, url_ordered_dict)

def get_all_url_dict():
    """
    获取项目中所有的url
    :return:
    """
    url_ordered_dict = OrderedDict()
    md = import_string(settings.ROOT_URLCONF)  # 根据字符串形式导入模块
    # for item in md.urlpatterns:
    #     print(item.urlconf_name)
    recursion_urls(None, '/', md.urlpatterns, url_ordered_dict)  # 递归获取所有路由
    return url_ordered_dict
